package com.bachelor.community.controller;

import cn.hutool.core.date.DateUtil;
import com.bachelor.community.model.entity.Collection;
import com.bachelor.community.service.intf.CollectionService;
import com.bachelor.community.utils.Result;
import com.bachelor.community.utils.UserSupport;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/collections")
public class CollectionController {
    @Resource
    private UserSupport userSupport;
    @Resource
    private CollectionService collectionService;

    /**
     * 收藏回答
     * @param collection 收藏
     * @return Result
     */
    @PostMapping
    public Result insertCollection(@RequestBody Collection collection) {
        Integer userId = userSupport.getCurrentUserId();
        collection.setUserId(userId);
        collection.setCreateTime(DateUtil.date());
        collectionService.save(collection);
        return Result.succeed("201", collection);
    }

    /**
     * 取消收藏
     * @param id 收藏ID
     * @return Result
     */
    @DeleteMapping("{id}")
    public Result deleteCollection(@PathVariable Integer id) {
        return Result.succeed("204", collectionService.removeById(id));
    }

    /**
     * 查询某用户的收藏夹
     * @param userId 用户ID
     * @return Result
     */
    @GetMapping("{userId}")
    public Result listCollections(@RequestParam("offset") Integer currentPage, @RequestParam("limit") Integer pageSize, @PathVariable Integer userId) {
        return Result.succeed("200", collectionService.listCollectionsByUserId(currentPage, pageSize, userId));
    }

    /**
     * 查询当前用户是否收藏过某回答
     * @param answerId 回答ID
     * @return Result
     */
    @GetMapping
    public Result getCollectionByAnswerId(@RequestParam("answerId") Integer answerId) {
        Integer userId = userSupport.getCurrentUserId();
        QueryWrapper<Collection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("answer_id", answerId);
        return Result.succeed("200", collectionService.getOne(queryWrapper));
    }
}
